package com.whut.coc.adapter.client;

import com.whut.coc.adapter.dto.PlayerDTO;
import com.whut.coc.util.HttpUtils;
import com.whut.coc.util.JsonUtils;
import com.whut.coc.util.TagUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 村庄信息获取Client
 * @Author: Zonghe Wang
 * @Date: 2025/6/22 13:56
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class COCClient {

    @Value("${coc.clash-of-clan.api-key}")
    private String API_KEY;

    public PlayerDTO getPlayerInfo(String tag) {
        String encodedTag = TagUtil.encodePlayerTag(tag);
        // API配置
        String apiUrl = "https://api.clashofclans.com/v1/players/" + encodedTag;

        // 设置请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "Bearer " + API_KEY);
        headers.put("Accept", "application/json");

        try {
            // 发送GET请求
            String jsonResponse = HttpUtils.get(apiUrl, headers);

            // 处理响应
            log.info("API响应：{}", jsonResponse);
            // 使用JsonUtils解析JSON到PlayerDTO
            return JsonUtils.jsonCovertToObject(jsonResponse, PlayerDTO.class);
        } catch (IOException e) {
            log.warn("获取玩家信息失败:{}", e.getMessage());
        }
        return null;
    }


}
